<template>
	<view class="rh-datetime-picker-container">
		<picker v-if="isDatePicker" mode="date" :fields="mode" @change="confirm" :value="emitValue" start="2021-01" end="2050-09">
			<view class="picker-content">
				<text :style="{
					'font-size': customStyle['font-size'],
					'color': customStyle['color']
				}" class="picker-txt">{{emitValue}}{{bar}} </text>
				<u-icon
						:color="customStyle['color']"
						name="arrow-down"
				></u-icon>
			</view>
		</picker>
		<picker v-else @change="confirm" :value="emitValue" range-key="label" :range="list">
			<view class="picker-content">
				<text :style="{
					'font-size': customStyle['font-size'],
					'color': customStyle['color']
				}" class="picker-txt">{{emitValue}}</text>
				<u-icon
						:color="customStyle['color']"
						name="arrow-down"
				></u-icon>
			</view>
		</picker>
		
	</view>
</template>

<script>
	export default {
		props: {
			value: [String, Number, Array],
			list: {
				type: Array,
				default: () => {return []}
			},
			bar: {
				type: String,
				default: () => {return ''}
			},
			customStyle: {
				type: Object,
				default: () => {
					return {
						'color': '#333',
						'font-size': '26rpx'
					}
				}
			},
			mode: {
				type: String,
				default: () => {return 'month'}
			}
		},
		computed: {
			isDatePicker(){
				let _self = this
				let boo = _self.mode == 'month' || _self.mode == 'year' ? true : false
				return boo
			},
		},
		data() {
			return {
				emitValue: ''
			};
		},
		mounted() {
			let _self = this
			if(_self.isDatePicker){
				_self.emitValue = _self.timestampToTime(Number(new Date()))
				_self.$emit('input', _self.emitValue)
			}else{
				console.log(_self.value)
				_self.emitValue = _self.value
			}
		},
		methods: {
			confirm(e){
				console.log(e)
				let _self = this, {value} = e.detail
				if(_self.isDatePicker){
					_self.emitValue = value
					_self.$emit('input', value)
					_self.$emit('change', value)
				}else{
					_self.emitValue = _self.list[value]['label']
					_self.$emit('input', _self.list[value]['label'])
					_self.$emit('change', _self.emitValue)
				}
			},
			timestampToTime(timestamp) {
				let _self = this
				let date = new Date(timestamp)
			  let Y = date.getFullYear();
			  let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1)
			  let D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate())
				if(_self.mode == 'month') return `${Y}-${M}`
				if(_self.mode == 'year') return `${Y}`
			}
		}
	}
</script>

<style scoped lang="scss">
	.rh-datetime-picker-container{
		width: 100%;
	}
	.picker-content{
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 10rpx;
		min-width: 130rpx;
	}
</style>
